import { useState } from "react";
import { useContext, createContext } from "react";

const MyContext = createContext()

export const  ContextDemo  = ({children}) => {
  const [person, setPerson] = useState({name: 'Tom', age: 18})
  const login = () => console.log('登录')
  const addAge  = () => setPerson({...person, age: person.age +1})
  const subAge  = () => setPerson({...person, age: person.age -1})
  const changePerson = () => setPerson({name: '夏天', age: 27})
  const {name, age} = person
  return(
    <>
      <h1>useContext的使用</h1>
      <h3>人员信息</h3>
      <ul>
        <li>姓名: {name}</li>
        <li>年龄: {age}</li>
      </ul>
      <MyContext.Provider value={{login, addAge, subAge, changePerson}}>
        {children}
      </MyContext.Provider>
    </>
  )

}

export const T1 = () => {
  const {login, addAge, subAge, changePerson} = useContext(MyContext)
  
  return (
    <>
      <h3>在后代组件内使用Context</h3>
      <button onClick={addAge}>增加年龄</button>
      <button onClick={subAge}>减小年龄</button>
      <button onClick={login}>登录</button>
      <button onClick={changePerson}>换人</button>
    </>
  )
}